<?php

namespace app\api\controller;

use app\admin\model\SeparateCode;
use app\admin\model\SeparateVideo;
use app\admin\model\Store;
use app\api\library\wechat\wechat_merchant\WxPayV3Controller;
use app\api\model\SeparateSet;
use app\api\model\wanlshop\ShopConfig;
use app\common\controller\Api;
use app\common\library\job\MysqlJob;
use service\MysqlJobService;
use think\cache\driver\Redis;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\Queue;
use think\Request;
use wechat\MiniProgramService;
use wechat\WechatController;

class StoreApi extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $noSign = ['get_code'];
    private Store $model;
        /**
     * @var array|mixed
     */
    private $params;// 允许调用接口的渠道
    private WechatController $wechat; // 不需要sub_mch_id

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->params = $this->request->param();
        $action = $this->request->action();
        if (!in_array($action, $this->noSign)) {
            if (empty($this->params['sub_mch_id']))
                $this->error("sub_mch_id 未传");
            $this->model = new Store();
        }
    }

    public function info()
    {
        $res = [];
        try {
            $res = $this->model->where(['sub_mch_id' => $this->params['sub_mch_id']])->find();
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            $this->error($e->getMessage());
        }
        if (empty($res)) {
            $this->error("该商户号不存在");
        }
        if (empty($res->store_image))
            $this->error("商户未上传图片");
        $res->store_image = $this->request->domain() . $res->store_image;
        $config = [];
        try {
            $config = ShopConfig::get(['sub_mch_id' => $this->params['sub_mch_id']]);
        } catch (DbException $e) {
            $this->error($e->getMessage());
        }
        if (empty($config))
            $res['intercept_password'] = "";
            else
            $res['intercept_password'] = $config->intercept_password;
        $arr = SeparateVideo::all(['store_id' => $res->id]);
        $res['video_number'] = $res['video_works'] = "";
        if (!empty($arr)) {
            $arr = collection($arr)->toArray();
            $random = rand(0, count($arr) - 1);
            $video = $arr[$random];
            $res['video_number'] = $video['video_number'];
            $res['video_works'] = $video['video_works'];
        }
        $this->success("success", $res);
    }

    public function payment()
    {
        $param = $this->request->param();
        $validate = new \think\Validate(
            [
                'amount' => 'number',
                'openid' => 'require',
                'sub_mch_id' => 'number'
            ]
        );
        if (!$validate->check($this->params)) {
            $this->error($validate->getError());
        }
        if (empty($param['body'])) {
            $this->params['body'] = "商户支付";
        }
        $this->params['order_id'] = date("YmdHis") . mt_rand(100000, 999999);
        $res = $this->model->where(['sub_mch_id' => $this->params['sub_mch_id']])->find();
        if (empty($res->service_secret))
            $this->error("该商户未配置service_secret");
        $this->secret = SeparateSet::get(['secret' => $res->service_secret]);
        // 创建后异步创建码
        Queue::push(MysqlJob::class, ["sub_mch_id"=>$this->params['sub_mch_id'],'secret'=>$this->secret,
            'openid'=>$this->params['openid']], 'bind_user');
        $this->wechat = new WechatController($this->params['sub_mch_id'], $this->secret);
        $res = $this->wechat->unifiedorder($this->params);
        if ($res['result_code'] == 'FAIL') {
            $this->error($res['result_message']);
        }
        $add = [];
        // 这里插入数据库
        $add['service_secret'] = $this->secret->secret;
        $add['other_order'] = $this->params['order_id'];
        $add['return_data'] = json_encode($res['data']);
        $add['state'] = 2;
        $add['body'] = $this->params['body'];
        $add['order_id'] = $this->params['order_id'];
        $add['notifyurl'] = config("site.notify_url");
        $add['amount'] = $this->params['amount'];
        $add['openid'] = $this->params['openid'];
        $add['sub_mch_id'] = $this->params['sub_mch_id'];
        $add['ip_addr'] = $_SERVER['REMOTE_ADDR'];
        $s = new \app\api\model\SeparateAccounts();
        $s->insert($add);
        // end
        $this->success("获取成功", $res['data']);
    }

    public function get_openid()
    {
        $data = $this->request->param();
        if (empty($data['code']) || empty($data['sub_mch_id']))
            $this->error("【sub_mch_id/code】不能为空");
        $res = $this->model->where(['sub_mch_id' => $this->params['sub_mch_id']])->find();
        $this->secret = SeparateSet::get(['secret' => $res->service_secret]);
        $mini = new MiniProgramService($this->secret);
        $res = $mini->get_openid($data['code']);
        $this->redis = new Redis();
        $this->redis->set("openid", json_encode($res));
        if (!empty($res['errcode']))
            $this->error($res['errmsg']);
        $this->success("获取成功", $res);
    }

    public function get_access_token()
    {
        $res = $this->model->where(['sub_mch_id' => $this->params['sub_mch_id']])->find();
        $this->secret = SeparateSet::get(['secret' => $res->service_secret]);
        $mini = new MiniProgramService($this->secret);
        $mini->access_token();
    }

    public function activa_code()
    {
        $res = SeparateCode::get(['number' => $this->params['code_id']]);
        if (empty($res))
            $this->error("该商户分享码未生成");
        if (!empty($res->sub_mch_id))
            $this->error("该码已被商户绑定");
        $val = SeparateCode::get(['sub_mch_id' => $this->params['sub_mch_id']]);
        if (!empty($val))
            $this->error("该商户已绑定收款码");
        $set = SeparateSet::get(['secret' => $res->service_secret])->find();
        $mini = new MiniProgramService($set);
        $path = "/path/to/directory/";
        $mini->generate_code(['param' => $this->params['sub_mch_id'],
                'path' => "pages/pay/index",
                'directory' => $path]
            , 'sub_mch_id');
        SeparateCode::update(['sub_mch_id' => $this->params['sub_mch_id'],
            'mini_code' => $path . $this->params['sub_mch_id'] . ".png"], ['id' => $res->id]);
        $this->success("绑定成功");
    }
    public function create_card(){
        // 创建后异步创建码
        $res = new MysqlJobService();
        $res->create_card($this->params);
        var_dump($res);die;
    }
}